
//
// 120316 - AH - (Bergen Off. Bibliotek *) Created.
// 120705 - AH - (Kryddar) Removed documented away code.
// 120714 - AH - Took FILE_ID in use.
//

package org.soekrat.server.servlets.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.DbFile;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements request to look up 
 *   {@link DbFile} that has text data.
 * </p>
 * @author Arne Halvorsen (AH) 
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class LookupTextFileHttpServlet 
  extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public LookupTextFileHttpServlet(){}
  
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res, "Lookup Text File");
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
      return;
    }
    
    if (!validate(res, def, req)) return;
    
    long key=def.fetch(FILE_ID.name(), req).getLongValue();
    
    SoekratDAO dao=new SoekratDAOFactory().create();
      
    DbFile file=dao.getFile(key);
          
    if (file==null)
    {
      respond(res, "File not found");
      return;
    }
        
    if (!file.text())
    {
      respond(res, "File is not text");
      return;
    }
            
    InputStream is=dao.getInputStream(file);
              
    List<String> content=new ArrayList<String>();
              
    BufferedReader br=new BufferedReader(new InputStreamReader(is, "utf-8"));
              
    String line=br.readLine();
    while (line!=null)
    {
      content.add(line);
      line=br.readLine();
    }
    
   respond(res, content);   
  }
 
  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef("/soekrat_server/lookup_text_file")
      .desc("Lookup Text File").parameter(FILE_ID);
  }
  
}
